<template>
  <!-- 多项输入的值 -->
  <div class="w-full flex items-center px-8" :style="{ width: '100%' }">
    <div v-if="formMode?.mode === 'view'">
      {{ selectValStr }}
    </div>
    <div v-else class="flex w-full">
      <mci-select
        v-model="selectVal"
        collapse-tags-tooltip
        :max-collapse-tags="1"
        :disabled="formMode?.mode === 'disable'"
        :filterable="true"
        :multiple="true"
        :allow-create="true"
        :default-first-option="true"
        :collapse-tags="true"
        class="w-full"
        @change="handleChange"
      >
        <mci-option v-for="item in combinedOptions" :key="item.value" :label="item.label" :value="item.value" />
        <template #footer>
          <div class="px-16">
            <mci-button :icon="'mci-icon-edit-1'" type="info" link @click="handleBatch">批量</mci-button>
          </div>
        </template>
      </mci-select>
      <div v-if="formMode?.mode === 'edit' && isVisible">
        <batch-tag :batch-vals="tagVals" @change="handleBatchChange" @close="isVisible = false" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { MciSelect, MciOption, MciButton } from '@/components/base';
import { BatchTag } from './BatchTag';
import { useFormMode } from '@/components/base/Form/mode';

const props = defineProps<{
  condValue: any;
}>();
const emit = defineEmits(['valueChange']);

const options = ref<any[]>([]);
const selectVal = ref<any>([]);

const formMode = useFormMode();

// 只读
const selectValStr = computed(() => {
  if (selectVal.value && selectVal.value.length > 0) {
    // return `${selectVal.value[0]} 等 ${selectVal.value.length - 1}项`;
    return selectVal.value;
  }
  return '';
});

// 批量编辑
const tagVals = ref<string[]>([]);
const handleBatch = () => {
  tagVals.value = selectVal.value;
  isVisible.value = true;
};

const handleBatchChange = (val: string[]) => {
  isVisible.value = false;
  selectVal.value = val;
  handleChange(val);
};

// 合并初始选项和创建的新选项
const combinedOptions = computed(() => [...options.value]);

const pushOptions = (list: any) => {
  list?.forEach((item: any) => {
    if (!options.value.some((option) => option.value === item)) {
      options.value.push({
        value: item,
        label: item
      });
    }
  });
};

const isVisible = ref(false);

// 初始化值
const buildValue = (oldValue?: any) => {
  if (oldValue && typeof oldValue === 'string') {
    try {
      const arr = JSON.parse(oldValue);
      if (formMode?.mode === 'view') {
        selectVal.value = arr.join('，');
      } else {
        selectVal.value = arr;
        pushOptions(arr);
      }
    } catch (error) {
      console.error(error);
    }
  }
};

buildValue(props.condValue);

watch(
  [() => props.condValue],
  ([newCondValue]) => {
    // selectVal.value = newCondValue;
    buildValue(newCondValue);
  },
  { deep: true }
);

const handleChange = (val: any) => {
  pushOptions(val);
  emit('valueChange', val);
};
</script>
